package com.rede.didiok.admin.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 百度SEO推送配置类
 *
 * @author 陌溪
 * @date 2020年12月31日21:26:43
 */
@Configuration
@Slf4j
public class BaiduSeoConfig {
    @Value("${seo.site}")
    private String site;
    @Value("${seo.token}")
    private String token;
    @Value("${seo.baiduSite}")
    private String baiduSite;

    public String getSite() {
        return site;
    }

    public String getToken() {
        return token;
    }


    /**
     * 推送到百度SEO
     *
     * @param site
     * @param token
     * @param urlsStr
     * @return
     */
    public String Post(String site, String token, String urlsStr) {
        StringBuilder result = new StringBuilder();
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            //建立URL之间的连接
            URLConnection conn = new URL(baiduSite + "?site=" + site + "&token=" + token).openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("Host", "data.zz.baidu.com");
            conn.setRequestProperty("User-Agent", "curl/7.12.1");
            conn.setRequestProperty("Content-Length", "83");
            conn.setRequestProperty("Content-Type", "text/plain");

            //发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //获取conn对应的输出流
            out = new PrintWriter(conn.getOutputStream());

            out.print(urlsStr);
            //进行输出流的缓冲
            out.flush();
            //通过BufferedReader输入流来读取Url的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.warn("推送到百度SEO异常", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    //Array转String
    public String urlsArrToString(String[] urlsArr) {
        String tempResult = "";
        for (int i = 0; i < urlsArr.length; i++) {
            if (i == urlsArr.length - 1) {
                tempResult += urlsArr[i].trim();
            } else {
                tempResult += (urlsArr[i].trim() + "\n");
            }
        }
        return tempResult;
    }

}
